package cn.stylefeng.guns.modular.recy.service;
/*
 */

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.*;
import cn.stylefeng.guns.modular.recy.mapper.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import org.springframework.stereotype.*;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RegionService extends ServiceImpl<RegionMapper, Region>
{
    public Region getRegionByNames(String regionsName){
        String[] regions = StrUtil.split(regionsName,"/");
        if(ObjectUtil.isNotNull(regions) && regions.length>1) {
            QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<>();
            regionQueryWrapper.lambda().eq(Region::getLevel, 2).eq(Region::getName, regions[0]).or().eq(Region::getLevel, 3).eq(Region::getName, regions[1]);
            if (regions.length > 2) {
                regionQueryWrapper.lambda().or().eq(Region::getLevel, 4).eq(Region::getName, regions[2]);
            }
            regionQueryWrapper.orderByAsc("level").orderByAsc("longcode");
            List<Region> list = getBaseMapper().selectList(regionQueryWrapper);
            if (list.size() > 0) {
                Region province = list.get(0);
                list = list.stream().filter(region -> {
                    return StrUtil.startWith(region.getLongcode(), province.getLongcode());
                }).collect(Collectors.toList());
                Region lastRegion = CollectionUtil.getLast(list);
                if (lastRegion != null) {
                    return lastRegion;
                }
            }
        }
        return null;
    }
}
